package com.mgy.api.example.parameter;

import com.mgy.api.framework.core.annotation.Action;
import com.mgy.api.framework.core.api.ApiResponse;
import com.mgy.api.framework.core.handler.ApiHandlerInterceptor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * xxx
 *
 * @author maguoyong
 * @date 2019/11/27
 */
@Component
public class MyApiHandlerInterceptor implements ApiHandlerInterceptor {

    /**
     * 方法前置参数校验
     */
    @Override
    public void preHandle(HttpServletRequest request, Method method, Action action) throws Exception {
        String platform = request.getParameter("platform");
        if (!"pdd".equals(platform)) {
            throw new IllegalArgumentException("platform不是pdd");
        }
    }


    /**
     * api返回值转换包装
     */
    @Override
    public Object postHandle(Method method, Action action, Object result) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", result);
        return resultMap;
    }

    /**
     * api异常自定义转换包装
     */
    @Override
    public Object exceptionHandle(Method method, Action action, Exception ex) throws Exception {
        ApiResponse response = new ApiResponse();
        response.setErrorCode("1000");
        response.setMsg("自定义异常:" + ex.getMessage());
        response.setSubMsg("method=" + action.value() + ";version=" + action.version());

        return response;
    }

}
